package com.am.server.api.system.dictionary.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.am.server.api.system.dictionary.dao.rdb.DictionaryItemDao;
import com.am.server.api.system.dictionary.model.dto.DictionaryItemDto;
import com.am.server.api.system.dictionary.model.dto.DictionaryItemListQueryDto;
import com.am.server.api.system.dictionary.model.dto.SaveDictionaryItemDto;
import com.am.server.api.system.dictionary.model.dto.UpdateDictionaryItemDto;
import com.am.server.api.system.dictionary.model.mapper.DictionaryItemMapper;
import com.am.server.api.system.dictionary.service.DictionaryItemService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 阮雪峰
 */
@Service
public class DictionaryItemServiceImpl implements DictionaryItemService {
    private final DictionaryItemDao dictionaryItemDao;
    private final DictionaryItemMapper dictionaryItemMapper;

    public DictionaryItemServiceImpl(DictionaryItemDao dictionaryItemDao, DictionaryItemMapper dictionaryItemMapper) {
        this.dictionaryItemDao = dictionaryItemDao;
        this.dictionaryItemMapper = dictionaryItemMapper;
    }

    @Override
    public List<DictionaryItemDto> find(DictionaryItemListQueryDto dto) {
        return dictionaryItemDao.find(dto).stream().map(dictionaryItemMapper::toDto).toList();
    }

    @Override
    public void save(SaveDictionaryItemDto dto) {
        dictionaryItemDao.save(dictionaryItemMapper.saveDtoToEntity(dto));
    }

    @Override
    public void update(UpdateDictionaryItemDto dto) {
        dictionaryItemDao.findById(dto.getId()).ifPresent(entity -> {
            BeanUtil.copyProperties(dto, entity, "id", "dictionaryId");
            dictionaryItemDao.save(entity);
        });
    }

    @Override
    public void delete(Long id) {
        dictionaryItemDao.delete(id);
    }
}
